package com.lap.auth.adapter.driving.ports;

import com.lap.auth.shared.ports.SeqService;
import com.lap.framework.common.tool.DateTimeUtil;
import java.time.LocalDate;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor
@Component
public class SeqServiceImpl implements SeqService {
  public static final Long ONE = 1L;
  public static final int TIME = 86400;

  private final StringRedisTemplate redisTemplate;

  /**
   * 获取序列号
   *
   * @param prefix 序号前缀
   * @return 序列化
   */
  public String getSeq(String prefix) {
    return getSeq(prefix, true);
  }

  /**
   * 获取序列号
   *
   * @param prefix 序号前缀
   * @param contain 是否包含前缀
   * @return 序列化
   */
  public String getSeq(String prefix, boolean contain) {
    String preKey = StringUtils.isNotBlank(prefix) ? prefix : "";
    String date = DateTimeUtil.formatCompactShortYearDate(LocalDate.now());

    ValueOperations<String, String> operations = redisTemplate.opsForValue();
    Long index = operations.increment((preKey + date), 1);
    if (ONE.equals(index)) {
      operations.getAndExpire((preKey + date), TIME, TimeUnit.SECONDS);
    }

    String value = StringUtils.leftPad(String.valueOf(index), 4, "0");
    return (contain ? preKey : "") + date + value;
  }
}
